package com.lottery.ruok.lottrey.fragment;

import android.Manifest;
import android.animation.Animator;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.AccountDetailActivity;
import com.lottery.ruok.lottrey.activity.ActivitiesCenterActivity;
import com.lottery.ruok.lottrey.activity.ChargeActivity;
import com.lottery.ruok.lottrey.activity.ChargeRecordActivity;
import com.lottery.ruok.lottrey.activity.FavorActivity;
import com.lottery.ruok.lottrey.activity.InfoAnnouncementActivity;
import com.lottery.ruok.lottrey.activity.MyRedPacketActivity;
import com.lottery.ruok.lottrey.activity.OrderActivity;
import com.lottery.ruok.lottrey.activity.PlayRuleActivity;
import com.lottery.ruok.lottrey.activity.SetActivity;
import com.lottery.ruok.lottrey.activity.UserRecommendActivity;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.ActivitiesCenterActivityObj;
import com.lottery.ruok.lottrey.eventbusObject.AddBetSuccess;
import com.lottery.ruok.lottrey.eventbusObject.ChargePush;
import com.lottery.ruok.lottrey.eventbusObject.GetAccountWithPush;
import com.lottery.ruok.lottrey.eventbusObject.LogOut;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRoomRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.UpdateNicknameRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.UploadAvatar;
import com.lottery.ruok.lottrey.retrofitModule.request.UserRecommendRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ActivityListResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetActivitiesKeysResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRoomResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.OperationSuccessResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.UserRecommendResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import glideHelp.GlideHelper;
import io.rong.imkit.RongIM;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ui.OberservableScrollView;
import utils.Utils;
/*
 * 个人中心
 * */

public class MemberMainFragment extends BaseMainFragment {
    private static final int WHAT_REFRESH = 111;
    @BindView(R.id.scrollView)
    OberservableScrollView scrollView;
    @BindView(R.id.navigateBar)
    TextView navigateBar;
    @BindView(R.id.avatars)
    ImageView avatars;
    @BindView(R.id.reloadImg)
    ImageView reloadImg;
    @BindView(R.id.logins)
    TextView logins;
    @BindView(R.id.geren)
    ImageView geren;
    @BindView(R.id.account)
    TextView account;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.reload)
    FrameLayout reload;
    @BindView(R.id.bet_notes)
    LinearLayout betNotes;
    @BindView(R.id.my_red_packet)
    LinearLayout my_red_packet;
    @BindView(R.id.accounts_detail)
    LinearLayout accountsDetail;
    @BindView(R.id.charge_notes)
    LinearLayout chargeNotes;
    @BindView(R.id.withdraw_notes)
    LinearLayout withdrawNotes;
    @BindView(R.id.withdraw)
    TextView withdraw;
    @BindView(R.id.charge)
    TextView charge;
    @BindView(R.id.play_rule)
    LinearLayout playRule;
    @BindView(R.id.my_favor)
    LinearLayout myFavor;
    @BindView(R.id.info_broadcast)
    LinearLayout infoBroadcast;
    @BindView(R.id.online_service)
    LinearLayout onlineService;
    @BindView(R.id.set)
    LinearLayout set;
    @BindView(R.id.nickname)
    View nickname;
    @BindView(R.id.username)
    View username;
    @BindView(R.id.username_account)
    TextView username_account;
    @BindView(R.id.anim_prize)
    LottieAnimationView animPrize;
    @BindView(R.id.recommend_num)
    TextView recommendNum;
    @BindView(R.id.activities_center)
    LinearLayout activitiesCenter;
    @BindView(R.id.activities_count)
    TextView activitiesCount;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_REFRESH:
                    reloadImg.setEnabled(true);
                    reloadImg.setSelected(true);
                    break;
            }
        }
    };
    private final static String ANALYTIC_VERSION = "1.0";
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";/* 头像名称 */
    private File tempFile;
    private int recommendNums = 0;
    private String mRecommendUrl;
    private ActivityListResponse activityListResponse;
    private Uri uritempFile;

    /*
     * 从相册获取
     */
    public void gallery() {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    /*
     * 从相机获取
     */
    public void camera() {
        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    PHOTO_FILE_NAME);
            // 从文件中创建uri
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }

    /*
     * 剪切图片
     */
    private void crop(Uri uri) {
        if (uri != null) {
            // 裁剪图片意图
            Intent intent = new Intent("com.android.camera.action.CROP");
            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            // 裁剪框的比例，1：1
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // 裁剪后输出图片的尺寸大小
            intent.putExtra("outputX", 250);
            intent.putExtra("outputY", 250);
            intent.putExtra("outputFormat", "JPEG");// 图片格式
            intent.putExtra("noFaceDetection", true);// 取消人脸识别
            intent.putExtra("return-data", true);

            //uritempFile为Uri类变量，实例化uritempFile  
 uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
 intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
 intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

            // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
            startActivityForResult(intent, PHOTO_REQUEST_CUT);
        }
    }

    /*
     * 判断sdcard是否被挂载
     */
    private boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            // 从相机返回的数据
            if (hasSdcard() && tempFile != null) {
                crop(Uri.fromFile(tempFile));
            } else {
                Utils.showToast("未找到存储卡，无法存储照片");
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            Bitmap bitmap=null;
            if (data != null) {
                try {
                   bitmap =       BitmapFactory.decodeStream(    getContext().getContentResolver().openInputStream(uritempFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
              //  final Bitmap bitmap = data.getParcelableExtra("data");
                if (bitmap != null) {
                    //create a file to write bitmap data
                    File file = new File(getActivity().getCacheDir(), "test.png");
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                    byte[] bitmapdata = bos.toByteArray();

                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(bitmapdata);
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

                    Call<ResponseBody> req = RetrofitBase.getRetrofit().create(UploadAvatar.class).postImage(requestBody, UserInfo.getToken(), 1, UserInfo.getUsername());
                    final Bitmap finalBitmap = bitmap;
                    req.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            Utils.showToast("头像上传成功");
                            try {
                                JSONObject jsonObj = new JSONObject(response.body().string());
                                UserInfo.setAvatar(jsonObj.getJSONArray("data").getJSONObject(0).getString("file"));
                                String photoUrl = jsonObj.getJSONArray("data").getJSONObject(0).getString("file");
                                RongIM.getInstance().refreshUserInfoCache(new io.rong.imlib.model.UserInfo(UserInfo.getMyUserId(), UserInfo.getUsername(), Uri.parse(photoUrl)));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            Bitmap bitmap1 = Utils.toRoundBitmap(finalBitmap);
                            avatars.setImageBitmap(bitmap1);
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            t.printStackTrace();
                        }
                    });
                }
            }
            try {
                // 将临时文件删除
                if (tempFile != null) {
                    tempFile.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private boolean isPrepared;
    private boolean mHasLoadedOnce;

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }

        init();

        mHasLoadedOnce = true;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess event) {
        setLoginState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(LogOut event) {
        setUnloginState();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddBetSuccess event) {
        if (event.getAfter_amount() != null) {
            UserInfo.setAccount(event.getAfter_amount());
            money.setText(UserInfo.getAccount());
        } else {
            getAccount(false);
        }
    }

    /**
     * 活动个数
     *
     * @param activityListResponse
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ActivitiesCenterActivityObj activityListResponse) {
        ArrayList<ActivityListResponse.ListBean> joninedActvities = new ArrayList<>();
        for (ActivityListResponse.ListBean listBean : activityListResponse.getmActivityListResponse().getList()) {
            /**
             * 去除暂停，过期，待发布的任务,已完成
             */
            ArrayList<ActivityListResponse.ListBean.MissionsBean> missions = listBean.getMissions();
            for (ActivityListResponse.ListBean.MissionsBean mission : missions) {
                if(mission.getStatus() == 3)listBean.setStatus(2);
            }
            if (listBean.getStatus() == 2) {//
                joninedActvities.add(listBean);
            }
        }
        if (Utils.isEmpty(UserInfo.getToken())) {
            activitiesCount.setText("参与进行中" + 0 + "个活动");
        } else {
            activitiesCount.setText("参与进行中" + joninedActvities.size() + "个活动");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ChargePush event) {
        getAccount(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GetAccountWithPush getAccountWithPush) {
        setLoginState();
    }

    private void setLoginState() {
        if (!UserInfo.getAvatar().equals("")) {
            GlideHelper.loadRoundImage(this, UserInfo.getAvatar(), avatars, R.mipmap.chat_default);
        }

        logins.setVisibility(View.GONE);

        geren.setVisibility(View.VISIBLE);
        account.setVisibility(View.VISIBLE);
        money.setVisibility(View.VISIBLE);
        reload.setVisibility(View.VISIBLE);
        username.setVisibility(View.VISIBLE);
        username_account.setVisibility(View.VISIBLE);
        nickname.setVisibility(View.VISIBLE);

        account.setText(UserInfo.getNickname());
        username_account.setText(UserInfo.getUsername());
        money.setText(UserInfo.getAccount());
    }

    private void setUnloginState() {
        avatars.setImageResource(R.mipmap.head_pic1);

        logins.setVisibility(View.VISIBLE);

        geren.setVisibility(View.GONE);
        account.setVisibility(View.GONE);
        money.setText("- - -");
        reload.setVisibility(View.GONE);
        username.setVisibility(View.GONE);
        username_account.setVisibility(View.GONE);
        nickname.setVisibility(View.GONE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.member_fragment, container, false);

        ButterKnife.bind(this, view);


        isPrepared = true;
        lazyLoad();
        reloadImg.setEnabled(true);
        reloadImg.setSelected(true);
        return view;
    }

    private void init() {
       /* DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
        int leftSide = Utils.dip2px(getContext(), 159) + charge.getMeasuredWidth() * 2;
        int diff = dm.widthPixels - leftSide;
        if (diff <= 0) {
            RelativeLayout.LayoutParams charge_params = (RelativeLayout.LayoutParams) charge.getLayoutParams();
            charge_params.setMargins(charge_params.leftMargin + diff - 10, Utils.dip2px(getContext(), 154), 0, 0);
            charge.setLayoutParams(charge_params);
        }
        if (dm.widthPixels <= 480) {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) withdraw.getLayoutParams();
            params.setMargins(10, Utils.dip2px(getContext(), 154), 0, 0);
            //params.setMargins(0, (int) (154 * dm.density), (int) (((dm.widthPixels / dm.density) - (139) - (110 * dm.density)) / 2), 0);
            withdraw.setLayoutParams(params);
        }*/
        if (UserInfo.getToken().equals("")) {
            //未登录
            setUnloginState();
        } else {
            //已登录
            setLoginState();
        }
    }

    private void getRecommend() {
        if (UserInfo.getToken().equals("")) {
            recommendNum.setVisibility(View.GONE);
        } else {
            RetrofitBase.getRetrofit().create(UserRecommendRequest.class)
                    .getResult(UserInfo.getToken(), 0, 10)
                    .compose(RxHelper.<UserRecommendResponse>handleResult())
                    .subscribe(new RxSubscribe<UserRecommendResponse>(getActivity()) {
                        @Override
                        protected void _onNext(UserRecommendResponse userRecommendResponse) {
                            recommendNums = userRecommendResponse.getUser_count();
                            recommendNum.setVisibility(View.VISIBLE);
                            recommendNum.setText(String.format("已推荐%s人", recommendNums));
                            mRecommendUrl = userRecommendResponse.getRecommend_url();
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getAccount(false);
        getRecommend();
        final int picW = Utils.dip2px(getActivity(), 54);
        final int picW_final = Utils.dip2px(getActivity(), 27);
        final int pic_d = picW - picW_final;

        final int tops = Utils.dip2px(getActivity(), 35);
        final int lefts = Utils.dip2px(getActivity(), 20);
        final int tops_final = Utils.dip2px(getActivity(), 27);
        final int lefts_final = Utils.dip2px(getActivity(), 23);
        final int left_d = lefts - lefts_final;
        final int top_d = tops - tops_final;
        scrollView.setScrollViewListener(new OberservableScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(OberservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                float h = y * 1.0f - Utils.dip2px(getContext(), 50);
                if (h >= 0) {
                    float bi = h / Utils.dip2px(getContext(), 50);
                    navigateBar.setAlpha(bi);

                    if (bi >= 0 && bi <= 1) {
                        avatars.getLayoutParams().height = (int) (picW - bi * pic_d);
                        avatars.getLayoutParams().width = (int) (picW - bi * pic_d);
                        ((FrameLayout.LayoutParams) avatars.getLayoutParams()).topMargin = (int) (tops - bi * top_d);
                        ((FrameLayout.LayoutParams) avatars.getLayoutParams()).leftMargin = (int) (lefts - bi * left_d);
                        avatars.requestLayout();
                    } else {
                        avatars.getLayoutParams().height = picW_final;
                        avatars.getLayoutParams().width = picW_final;
                        ((FrameLayout.LayoutParams) avatars.getLayoutParams()).topMargin = tops_final;
                        ((FrameLayout.LayoutParams) avatars.getLayoutParams()).leftMargin = lefts_final;
                        avatars.requestLayout();
                    }
                } else if (h < 0) {
                    navigateBar.setAlpha(0);

                    avatars.getLayoutParams().height = picW;
                    avatars.getLayoutParams().width = picW;
                    ((FrameLayout.LayoutParams) avatars.getLayoutParams()).topMargin = tops;
                    ((FrameLayout.LayoutParams) avatars.getLayoutParams()).leftMargin = lefts;
                    avatars.requestLayout();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions.length > 0 && grantResults.length > 0) {
            PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        }
    }

    @PermissionSuccess(requestCode = 100)
    public void doSomething() {
        Utils.createDialog(getActivity(), "请选择一张图片", "照相", "相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                camera();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                gallery();
            }
        });
    }

    @PermissionFail(requestCode = 100)
    public void doFailSomething() {
        Utils.showToast("访问相册失败");
    }

    private void getAccount(boolean progress) {
        if (!UserInfo.getToken().equals("")) {
            updateAccount(new AfterUpdateAccount() {
                @Override
                public void afterUpdateAccount(GetProfileResponse getProfileResponse) {
                    UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                    UserInfo.setUsername(getProfileResponse.getUser().getUsername());
                    UserInfo.setNickname(getProfileResponse.getUser().getNickname());
                    UserInfo.setMobilePhone(getProfileResponse.getUser().getMobile_phone());
                    UserInfo.setUserId(getProfileResponse.getUser_id());
                    UserInfo.setChatroom_block(getProfileResponse.getUser().getChatroom_block());
                    account.setText(UserInfo.getNickname());
                    money.setText( UserInfo.getAccount());
                    username_account.setText(UserInfo.getUsername());
                }
            }, progress);
        }
    }

    @OnClick({R.id.account,R.id.geren, R.id.my_red_packet, R.id.logins, R.id.reloadImg, R.id.bet_notes, R.id.accounts_detail, R.id.charge_notes, R.id.withdraw_notes, R.id.play_rule, R.id.my_favor, R.id.info_broadcast, R.id.online_service, R.id.withdraw, R.id.charge, R.id.set, R.id.avatars, R.id.recommend_layout, R.id.activities_center})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.recommend_layout:
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1 && UserInfo.getIsTry() != 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        Intent intent = new Intent(getActivity(), UserRecommendActivity.class);
                        intent.putExtra("recommendNums", recommendNums);
                        intent.putExtra("mRecommendUrl", mRecommendUrl);
                        startActivity(intent);
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.account:
                //修改昵称
                resetNickName();
                break;
            case R.id.geren:
                //修改昵称
                resetNickName();
                break;
            case R.id.accounts_detail:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_accountdetail_jump");
                if (!UserInfo.getToken().equals("")) {
                    Intent intent_red = new Intent(getActivity(), AccountDetailActivity.class);
                    startActivity(intent_red);
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.my_red_packet:
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1 && UserInfo.getIsTry() != 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        Intent intent_red = new Intent(getActivity(), MyRedPacketActivity.class);
                        startActivity(intent_red);
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.avatars:
                if (!UserInfo.getToken().equals("")) {
                    PermissionGen.with(this)
                            .addRequestCode(100)
                            .permissions(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .request();
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.set:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_jump");
                startActivity(new Intent(getActivity(), SetActivity.class));
                break;
            case R.id.logins:
                gotoLoginActivity();
                break;
            case R.id.reloadImg:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_wallet_refresh");
                reloadImg.setVisibility(View.GONE);
                animPrize.setVisibility(View.VISIBLE);
                animPrize.playAnimation();
                animPrize.addAnimatorListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animator) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animator) {
                        animPrize.setVisibility(View.GONE);
                        reloadImg.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animator) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animator) {

                    }
                });

                getAccount(true);
                break;
            case R.id.bet_notes:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_betrecord_jump");
                if (!UserInfo.getToken().equals("")) {
                    //切换到第四个tab栏
                    startActivity(new Intent(getActivity(), OrderActivity.class));
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.charge_notes:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_reward_jump");
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1 && UserInfo.getIsTry() != 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        Intent intent_account_detail = new Intent(getActivity(), ChargeRecordActivity.class);
                        intent_account_detail.putExtra("type", 1);
                        startActivity(intent_account_detail);
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.withdraw_notes:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_withdraw_record_jump");
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1 && UserInfo.getIsTry() != 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        Intent intent_account_detail = new Intent(getActivity(), ChargeRecordActivity.class);
                        intent_account_detail.putExtra("type", 2);
                        startActivity(intent_account_detail);
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.play_rule:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_lottery_rule_jump");
                Intent intent = new Intent(getActivity(), PlayRuleActivity.class);
                startActivity(intent);
                break;
            case R.id.my_favor:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_collection_jump");
                if (!UserInfo.getToken().equals("")) {
                    Intent intent_favor = new Intent(getActivity(), FavorActivity.class);
                    startActivity(intent_favor);
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.info_broadcast:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_infonotice_jump");
                Intent info_announcements = new Intent(getActivity(), InfoAnnouncementActivity.class);
                startActivity(info_announcements);
                break;
            case R.id.online_service:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_online_consult_jump");
//                if (UserInfo.getToken().equals("")) {
//                    gotoLoginActivity();
//                } else {
//                    if (UserInfo.getRoomId() != 0) {
//                        Intent intents = new Intent(getActivity(), ConversationActivity.class);
//                        intents.putExtra(ConversationUIService.GROUP_ID, UserInfo.getRoomId());
//                        startActivity(intents);
//
//                        Utils.showToast( "请咨询群里的管理员或客服");
//                    } else {
//                        Utils.showToast( "您暂时没有加入聊天房间");
//                    }
//                }

//                getService();

                Utils.openBrowser(Common.service_url, getActivity());
                break;
            case R.id.withdraw:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_withdraw_jump");
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        withdrawMoney();
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.charge:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_recharge_jump");
                if (!UserInfo.getToken().equals("")) {
                    if (UserInfo.getIsTest() == 1) {
                        Utils.showToast(Common.IS_TEST);
                    } else {
                        Intent intent1 = new Intent(getActivity(), ChargeActivity.class);
                        startActivity(intent1);
                    }
                } else {
                    gotoLoginActivity();
                }
                break;
            case R.id.activities_center:
                Intent activitiesCenterIntent = new Intent(getActivity(), ActivitiesCenterActivity.class);
                activitiesCenterIntent.putExtra("activities_response", activityListResponse);
                startActivity(activitiesCenterIntent);
                break;
        }
    }

    private void resetNickName() {
        //修改昵称
        final EditText editText = new EditText(getActivity());
        editText.setTextColor(Color.parseColor("#3f3f3f"));
        editText.setText(account.getText().toString());
        editText.setSelection(account.getText().toString().length());
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle("修改昵称")//设置提示内容
                .setView(editText)
                //确定按钮
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        RetrofitBase.getRetrofit().create(UpdateNicknameRequest.class)
                                .getResult(UserInfo.getToken(), editText.getText().toString())
                                .compose(RxHelper.<OperationSuccessResponse>handleResult())
                                .subscribe(new RxSubscribe<OperationSuccessResponse>(getActivity()) {
                                    @Override
                                    protected void _onNext(OperationSuccessResponse removeFavorResponse) {
                                        account.setText(editText.getText().toString());
                                        UserInfo.setNickname(editText.getText().toString());
                                        RongIM.getInstance().refreshUserInfoCache(new io.rong.imlib.model.UserInfo(UserInfo.getMyUserId(), editText.getText().toString(), Uri.parse(UserInfo.getAvatar())));
                                        RetrofitBase.getRetrofit().create(GetRoomRequest.class)
                                                .getResult(UserInfo.getToken(), UserInfo.getUsername())
                                                .compose(RxHelper.<GetRoomResponse>handleResult())
                                                .subscribeWith(new RxSubscribe<GetRoomResponse>(getActivity()) {
                                                    @Override
                                                    protected void _onNext(GetRoomResponse getRoomResponse) {

                                                    }

                                                    @Override
                                                    protected boolean showDialog() {
                                                        return false;
                                                    }
                                                });
                                    }

                                    @Override
                                    protected boolean showDialog() {
                                        return true;
                                    }
                                });
                    }
                })
                //取消按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .create();//创建对话框
        dialog.show();//显示对话框
        dialog.getButton(Dialog.BUTTON_NEGATIVE).setTextColor(getActivity().getResources().getColor(com.android.lib.R.color.purples));
        dialog.getButton(Dialog.BUTTON_POSITIVE).setTextColor(getActivity().getResources().getColor(com.android.lib.R.color.purples));
    }

    /**
     * 活动开关
     *
     * @param activitiesKeysResponse
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GetActivitiesKeysResponse activitiesKeysResponse) {
        if (activitiesKeysResponse.getEnable_activities() == 0) {
            activitiesCenter.setVisibility(View.GONE);
        } else {
            activitiesCenter.setVisibility(View.VISIBLE);
        }
    }
}